package com.tdcoding.chat.dbase;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.tdcoding.chat.entities.RegionInfo;
import com.tdcoding.chat.helper.Logger;
import com.tdcoding.chat.manager.DBManager;

/**
 * 地区管理
 * 
 * @author Wellsa
 *
 */
public class DBForRegion {
	private static final String TAG = "DBForRegion";
	private static final String TABLE = "ofRegion";

	/**
	 * 查询地域信息
	 * @param regionId
	 * @param type
	 * @return
	 */
	public static RegionInfo queryRegionInfo(long regionId,int type) {
		RegionInfo regionInfo = null;
		String where = "regionId=" + regionId+" and type="+type;
		String sql = "select * from "+TABLE+" where " + where;
		try {
			ResultSet resultSet = DBManager.querySql(0,
					sql);
			if (resultSet.first()) {
				regionInfo =new RegionInfo();
				regionInfo.setProId(resultSet.getInt("proId"));
				regionInfo.setCityId(resultSet.getInt("cityId"));
				regionInfo.setAreaId(resultSet.getInt("areaId"));
				regionInfo.setProName(resultSet.getString("proName"));
				regionInfo.setCityName(resultSet.getString("cityName"));
				regionInfo.setAreaName(resultSet.getString("areaName"));
				return regionInfo;
			}
			Logger.println(TAG, "queryRegionInfo", regionInfo);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加地区
	 * 
	 * @param set
	 * @param where
	 * @return
	 */
	static final String COLUMNS="regionId,proId,cityId,areaId,proName,cityName,areaName";
	public static int addRegionInfo(long regionId, RegionInfo regionInfo) {
		String values = regionId+","+regionInfo.getProId()+","
									+regionInfo.getCityId()+","
									+regionInfo.getAreaId()+","
									+"'" + regionInfo.getProName() 
									+ "','"+regionInfo.getCityName() 
									+ "','"+regionInfo.getAreaName()+"'";
		int result = DBManager.insertSql(0,TABLE, COLUMNS, values);
		return result;
	}

	/**
	 * 更新地区
	 * 
	 * @param set
	 * @param where
	 * @return
	 */
	public static int updateRegionInfo(long regionId,int type,RegionInfo regionInfo) {
		RegionInfo existRegion = queryRegionInfo(regionId,type);
		if (existRegion == null) {
			return addRegionInfo(regionId, regionInfo);
		}
		String where = "regionId=" + regionId;
		String set = "proId=" + regionInfo.getProId() + ",cityId="
				+ regionInfo.getCityId() + ",areaId=" + regionInfo.getAreaId()
				+ ", proName='" + regionInfo.getProName() + "', cityName='"
				+ regionInfo.getCityName() + "', areaName='"
				+ regionInfo.getAreaName() + "'";
		return DBManager.updateSql(0, TABLE, set,
				where);
	}
}
